package utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import kitwee.com.kanpad.MyMultiDexApplication;

public final class DeviceUtils {

    private DeviceUtils() {
        throw new UnsupportedOperationException("hey, buddy, easy...");
    }

    private static String televisionId = null;

    /**
     * 获取id
     */
    public static String getPadionId() {
        if (televisionId == null) {
            synchronized (DeviceUtils.class) {
                if (televisionId == null) {
                    return televisionId = getDeviceId(MyMultiDexApplication.getContext());
                }
            }
        }
        return televisionId;
    }

    /**
     * 获取设备id
     */
    public static String getDeviceId(Context context) {
        String deviceId = getAndroidId(context);
        if (!isValidAndroidId(deviceId)) {
            deviceId = getEthernetMacAddress();
            deviceId = deviceId.replaceAll(":", "").concat("0000");
        }
        return deviceId;
    }

    /**
     * 是否为有效的ANDROID ID
     *
     * @param androidId id
     */
    public static boolean isValidAndroidId(String androidId) {
        return !TextUtils.isEmpty(androidId) && !INVALID_ANDROID_ID.equals(androidId);
    }

    /**
     * 获取ANDROID ID
     *
     * @param context 上下文
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 获取以太网MAC地址
     */
    public static String getEthernetMacAddress() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/sys/class/net/eth0/address"));
            String ethMac = reader.readLine();
            if (TextUtils.isEmpty(ethMac)) {
                ethMac = DEFAULT_MAC_ADDRESS;
            }
            return ethMac;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return DEFAULT_MAC_ADDRESS;
    }

    private static final String INVALID_ANDROID_ID = "9774d56d682e549c";

    private static final String DEFAULT_MAC_ADDRESS = "02:00:00:00:00:00";

}
